package com.mocchira.music.radio;

import java.io.File;
import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

public class FavoriteLists {
    private Context context;
    private File file;
    private JSONObject root;

    private static final String FAVORITE_FNAME = "favorite.json";
    private static final int MAX_ITEM = 30;
    
    public FavoriteLists(Context con) {
        context = con;
        file = new File(con.getFilesDir(), FAVORITE_FNAME);
        if (file.canRead()) {
            try {
                read();
            } catch (Exception ex) {
                root = new JSONObject();
            }
        } else {
            root = new JSONObject();
        }
    }
    protected void read() throws Exception {
        String ret = FileUtil.getContents(file);
        root = new JSONObject(ret);
    }
    protected void write() throws Exception {
        FileUtil.putContents(root.toString(), File.createTempFile(this.toString(), ".json", context.getCacheDir()), file);
    }
    protected String genKey(JSONObject obj) throws JSONException {
        return obj.getString("artist_name") + "_" + obj.getString("album_name") + "_" + obj.getString("track_name");
    }
    public void add(JSONObject obj) throws JSONException {
        if (root.length() >= MAX_ITEM) return;
        root.put(genKey(obj), obj);
    }
    public void delete(JSONObject obj) throws JSONException {
        root.remove(genKey(obj));
    }
    public boolean isExist(JSONObject obj) {
        String key = "";
        try {
            key = genKey(obj);
        } catch (Exception ex) {
            return false;
        }
        return root.has(key);
    }
    public JSONObject get(String key) {
        try {
            return (JSONObject)root.get(key);
        } catch (Exception ex) {
            return null;
        }
    }
    public void finalize() {
        try {write();}catch (Exception ex){};
    }
    public Iterator<String> iterator() {
        @SuppressWarnings("unchecked")
        Iterator<String> keys = root.keys();
        return keys;
    }
    public boolean addable() {
        return root.length() < MAX_ITEM;
    }
    public int length() {
        return root.length();
    }
}
